package com.xiqi.microservice.zuul.config;

import com.xiqi.microservice.auth.config.JWTAuthenticationConfig;
import com.xiqi.microservice.auth.filter.JWTTokenAuthenticationFilter;
import org.apache.http.HttpRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;

/**
 * @program: apigateway
 * @description:
 * @author: Shine
 * @create: 2019-08-01 14:11
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private JWTAuthenticationConfig jwtAuthenticationConfig;

    @Bean
    public JWTAuthenticationConfig jwtAuthenticationConfig(){
        JWTAuthenticationConfig jwtAuthenticationConfig = new JWTAuthenticationConfig();
        return jwtAuthenticationConfig;
    }
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().logout().disable().formLogin().disable().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
                .anonymous().and().exceptionHandling().authenticationEntryPoint(
                (req,res,e)->res.sendError(HttpServletResponse.SC_UNAUTHORIZED)
        ).and().addFilterAfter(new JWTTokenAuthenticationFilter(jwtAuthenticationConfig), UsernamePasswordAuthenticationFilter.class)
                .authorizeRequests().antMatchers("此处写路径").hasRole("此处写权限").antMatchers("此处写路径").permitAll()
                .antMatchers(jwtAuthenticationConfig.getUrl()).permitAll();
    }
}
